package scutiger.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import scutiger.annotation.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public abstract class AbsController implements BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;

    @Override
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    @Override
    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    /**输出信息到jsp页面
     * @param msg 需要输出的信息
     */
    protected void print(Object msg){
        try {
            response.getWriter().print(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**打印一个json数据
     * @param msg
     */
    protected void printJson(Object msg){
        String s = JSON.toJSONString(msg);
        try {
            response.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**打印成功消息 带数据
     * @param data  数据
     * @param msg 消息提示
     */
    protected void printSuccess(Object data,String msg){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",true);
        jsonObject.put("data",data);
        jsonObject.put("msg",msg);
        String s = jsonObject.toJSONString();
        try {
            response.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**打印成功消息 不带数据
     * @param msg  消息
     */
    protected void printSuccess(String msg){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",true);
        jsonObject.put("msg",msg);
        String s = jsonObject.toJSONString();
        try {
            response.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**打印成功消息 不带数据
     * @param msg  消息
     */
    protected void success(String msg){
        printSuccess(msg);
    }

    /**打印错误信息
     * @param msg 错误消息
     */
    protected void printFail(String msg){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",false);
        jsonObject.put("msg",msg);
        String s = jsonObject.toJSONString();
        try {
            response.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**打印错误信息
     * @param msg 错误消息
     */
    protected void fail(String msg){
        printFail(msg);
    }
}
